package com.wokeMy.view.Lottery;

import android.app.Dialog;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongcai.online.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.wokeMy.view.adpter.DoubleGridBallAdapter;
import com.wokeMy.view.adpter.LastBatAdapter;
import com.wokeMy.view.base.BaseActivity;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.model.DoubleLo;
import com.wokeMy.view.util.Util;
import com.wokeMy.view.util.ViewTools;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class HappyBallActivity extends BaseActivity {
    RecyclerView redGridRv,buleGridRv;
    ListView lastLv;
    RelativeLayout lastRl;
    ImageView expendIv,double_bet_back;
    TextView zhuTv,monTv,delete_double_tv,head_happy_qishu,top_happy_time,top_happy_qh,head_happy_num;
    TextView shakeLL;
    List<String> data=new ArrayList<String>();
    List<String> blueData=new ArrayList<String>();
    NestedScrollView nestedScrollView;
    private SensorManager sensorManager;
    private Vibrator vibrator;
    private static final String TAG = "BettingActivity";
    private static final int SENSOR_SHAKE = 10;

    DoubleGridBallAdapter redBallAdapter;
    DoubleGridBallAdapter blueBallAdapter;
    ArrayList<String> redRandomBall, blueRandomBall;

    LastBatAdapter lastBatAdapter;
    boolean lastLvFlag;
    Button double_ok;
    int ballNumber=0; // Red+blue sum

    /**
     *
     * 动作执行
     */
    Handler handler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SENSOR_SHAKE:
//                    Toast.makeText(HappyBallActivity.this, "检测到摇晃，执行操作！", Toast.LENGTH_SHORT).show();
//                    Log.i(TAG, "检测到摇晃，执行操作！");
                    redRandomBall = Util.createRandom(35, 5);
                    blueRandomBall = Util.createRandom(12, 2);
                    Log.e("onCreate", redRandomBall.toString()+"0000000000");
                    redBallAdapter.setRandomBall(redRandomBall);
                    redBallAdapter.notifyDataSetChanged();
                    blueBallAdapter.setRandomBall(blueRandomBall);
                    blueBallAdapter.notifyDataSetChanged();
                    //                    zhuTv.setText(1+"注");
                    //                    monTv.setText(1+"元");


                    break;
            }
        }

    };
    ArrayList<DoubleLo> expendData;
    String user_id;
    Dialog mydialog;
    ArrayList<DoubleLo> doubleLos;
    DoubleLo zuiXingDouble,touDouble;
    @Override
    public void setContentView() {
        setContentView(R.layout.activity_happy_ball);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    }

    @Override
    public void initActivity() {
        expendData=new ArrayList<>();
        lastBatAdapter=new LastBatAdapter(getApplicationContext(),doubleLos);
        lastLv.setAdapter(lastBatAdapter);
        ViewTools.setListViewHeightBasedOnChildrenItem(lastLv,5);
        lastLv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                nestedScrollView.requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
        lastRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (lastLvFlag){
                    expendIv.setBackgroundResource(R.mipmap.arrow_down);
                    lastLv.setVisibility(View.GONE);

                }else {
                    expendIv.setBackgroundResource(R.mipmap.arrow_up);
                    lastLv.setVisibility(View.VISIBLE);
                }
                lastLvFlag=!lastLvFlag;
            }
        });

        redBallAdapter=new DoubleGridBallAdapter(data,getApplicationContext(),false,zhuTv,monTv);
        blueBallAdapter=new DoubleGridBallAdapter(blueData,getApplicationContext(),true,zhuTv,monTv);
        redBallAdapter.setGridBallAdapter(blueBallAdapter);
        blueBallAdapter.setGridBallAdapter(redBallAdapter);

        redGridRv.setLayoutManager(new GridLayoutManager(this,8));
        buleGridRv.setLayoutManager(new GridLayoutManager(this,8));
        redGridRv.setAdapter(redBallAdapter);
        buleGridRv.setAdapter(blueBallAdapter);

        redGridRv.setNestedScrollingEnabled(false);
        redGridRv.setNestedScrollingEnabled(false);

        //        ballNumber=redRandomBall

        shakeLL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vibrator.vibrate(100);
                Message msg = new Message();
                msg.what = SENSOR_SHAKE;
                handler.sendMessage(msg);
            }
        });
        double_bet_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        double_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (redBallAdapter.getChenckBall().size()>=5&&blueBallAdapter.getChenckBall().size()>=1){
                    String trim = monTv.getText().toString().trim();
                    int money = Integer.valueOf(trim.replace("元", ""));
                    if (money>20000){
                        tishi("单次投注最多2万元");
                    }else {
                        Intent intent=new Intent(HappyBallActivity.this,TicketActivity.class);
                        intent.putExtra("blueBall", Util.ballSort(redBallAdapter.getChenckBall()));
                        intent.putExtra("redBall",Util.ballSort( blueBallAdapter.getChenckBall()));
                        intent.putExtra("orderissue", zuiXingDouble.getIssue());
                        intent.putExtra("zhuTv", zhuTv.getText().toString().trim());
                        intent.putExtra("monTv", monTv.getText().toString().trim());
                        intent.putExtra("lotteryid", "106");
                        startActivity(intent);
                    }

                }else {
                    tishiToast("至少选择5个红球和1个蓝球");
                }

                //                Intent intent=new Intent(DoubleBallActivity.this,TicketActivity.class);
                //                startActivity(intent);
            }
        });
        delete_double_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                redRandomBall.clear();
                blueRandomBall.clear();
                blueBallAdapter.notifyDataSetChanged();
                redBallAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void initView() {
        redGridRv=myFindViewById(R.id.redGridRecyclerView_double);
        buleGridRv=myFindViewById(R.id.blueGridRecyclerView_double);
        shakeLL=myFindViewById(R.id.shake_double_ll);
        lastLv=myFindViewById(R.id.last_double_lv);
        lastRl=myFindViewById(R.id.last_double_rl);
        expendIv=myFindViewById(R.id.expand_double_lv);
        zhuTv=myFindViewById(R.id.zhu_double_tv);
        monTv=myFindViewById(R.id.money_double_tv);
        double_bet_back=myFindViewById(R.id.double_bet_back);

        double_ok=myFindViewById(R.id.double_ok);
        delete_double_tv=myFindViewById(R.id.delete_double_tv);
        top_happy_time=myFindViewById(R.id.top_happy_time);
        top_happy_qh=myFindViewById(R.id.top_happy_qh);
        head_happy_qishu=myFindViewById(R.id.head_happy_qishu);
        head_happy_num=myFindViewById(R.id.head_happy_num);
        nestedScrollView=myFindViewById(R.id.happy_scll);
    }

    @Override
    public void initData() {
        for (int i=1;i<=35;i++) {
            data.add(i+"");
        }
        for (int i=1;i<=12;i++) {
            blueData.add(i+"");
        }
        doubleLos=new ArrayList<>();
        mydialog=Util.createLoadingDialog(HappyBallActivity.this);
        queryLotteryList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sensorManager != null) {// 注册监听器
            sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
            // 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (sensorManager != null) {// 取消监听器
            sensorManager.unregisterListener(sensorEventListener);
        }
    }

    /**
     * 重力感应监听
     */
    private SensorEventListener sensorEventListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            // 传感器信息改变时执行该方法
            float[] values = event.values;
            float x = values[0]; // x轴方向的重力加速度，向右为正
            float y = values[1]; // y轴方向的重力加速度，向前为正
            float z = values[2]; // z轴方向的重力加速度，向上为正
            Log.i("BettingActivity", "x轴方向的重力加速度" + x +  "；y轴方向的重力加速度" + y +  "；z轴方向的重力加速度" + z);
            // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
            int medumValue = 15;// 如果不敏感自行调低该数值,低于10的话就不行了,因为z轴上的加速度本身就已经达到10了
            if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {
                if (!fastClickNoToast()){
                    vibrator.vibrate(200);
                    Message msg = new Message();
                    msg.what = SENSOR_SHAKE;
                    handler.sendMessage(msg);
                }else {
                    //                        Toast.makeText(BettingActivity.this, "请勿重复摇晃，！", Toast.LENGTH_SHORT).show();
                }
            }

        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };
    // 查询奖期列表
    public void  queryLotteryList(){
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("lotteryid","106");//玩法代码 118//双色球  106 大乐透
        Log.e("查询奖期列表params",params.toString());
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.CPLIST_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                closeLoadDial(mydialog);
                String result = null;
                try {
                    result = new String(bytes, "utf-8");
                    //                        Toast.makeText(SeletCardActivity.this, result, Toast.LENGTH_SHORT).show();
                    Log.e("查询奖期列表result", result);
                    try {
                        JSONObject jsonObject =new JSONObject(result);
                        if (jsonObject.get("flag").equals("success")) {
                            Gson gson = new Gson();
                            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("data");
                            for (int i1 = 0; i1 < jsonArray.length(); i1++) {
                                DoubleLo doubleLo = gson.fromJson(jsonArray.getString(i1), DoubleLo.class);
                                // status -1新奖期可预售 0新奖期开期通知 2奖期期结通知  3奖期开始开奖通知 7奖期开奖完成通知
                                if (i1==0){
                                    zuiXingDouble=doubleLo;
                                    top_happy_qh.setText("第"+zuiXingDouble.getIssue()+"期开奖结果：");
                                    top_happy_time.setText(zuiXingDouble.getEndtime());
                                }else if (i1==1){
                                    touDouble=doubleLo;
                                    head_happy_qishu.setText("第"+touDouble.getIssue()+"期开奖结果：");
                                    if (doubleLo.getStatus().equals("2")){
                                        head_happy_num.setText("待开奖");
                                    }else {
                                        head_happy_num.setText(Html.fromHtml(Util.dealtIssueDuo(touDouble.getBonuscode(),2)));
                                    }
                                }else {
                                    doubleLos.add(doubleLo);
                                }
                            }
                            Log.e("doubleLos",""+doubleLos.toString());
                            ViewTools.setListViewHeightBasedOnChildrenItem(lastLv,5);
                            lastBatAdapter.notifyDataSetChanged();
                        } else {
                            String info = jsonObject.getString("info");
                            if (jsonObject.has("data")){
                                info=jsonObject.getJSONObject("data").getJSONObject("data").getString("dealmsg");
                            }
                            tishi(info);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }
            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                closeLoadDial(mydialog);
            }
        });
    }
}
